<template>
  <div class="tree-box">
    <el-row>
      <el-input
        placeholder="搜索"
        v-model="filterText"
        style="margin-right: 10px"
      ></el-input>
    </el-row>
    <el-row class="page-aside-grow">
      <el-tree
        v-loading="loadTree"
        element-loading-text="数据加载中..."
        ref="tree"
        node-key="id"
        class="filter-tree"
        :data="treeData"
        :props="treeProps"
        :highlight-current="true"
        :default-expanded-keys="treeExpand"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        @node-click="nodeClick"
      ></el-tree>
    </el-row>
  </div>
</template>

<script setup>
import {ref, watch, onMounted} from 'vue';
import {useOrganizationStore} from '@/pinia/modules/organization';

const emit = defineEmits(['handleNodeClick']);

const filterText = ref('');
const loadTree = ref(false);
const treeData = ref([]);
const treeProps = ref({
  children: 'children',
  label: 'text'
});
const treeExpand = ref(['0']);
const tree = ref();
const organizationStore = useOrganizationStore();

const filterNode = (value, data) => {
  if (!value) return true;
  return data.text.indexOf(value) !== -1
    || (data.data != null && data.data.code != null && data.data.code.indexOf(value) !== -1);
};

const nodeClick = (data) => {
  emit("handleNodeClick", data);
};

const loadOrganization = async(id) => {
  loadTree.value = true
  treeData.value = await organizationStore.getOrganization();
  treeExpand.value = [treeData.value && treeData.value[0] && treeData.value[0].id, id || '0'];
  loadTree.value = false
};

watch(() => filterText.value, (val) => {
  tree.value.filter(val);
});

onMounted(() => {
  loadOrganization();
});

defineExpose({ loadOrganization });
</script>

<style lang="scss" scoped>
.tree-box {
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>